<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>猜数字游戏 - 完整版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 0;
            text-align: center;
            margin-bottom: 20px;
            border-radius: 10px;
        }

        .header h1 {
            color: white;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            color: rgba(255, 255, 255, 0.9);
            font-size: 1.1em;
        }

        .player-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .connection-control {
            background: #fff;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            text-align: center;
        }

        .connection-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin: 15px 0;
        }

        .connection-status {
            font-weight: bold;
            padding: 8px 16px;
            border-radius: 20px;
            display: inline-block;
            margin-top: 10px;
        }

        .connection-status.connected {
            background: #d4edda;
            color: #155724;
        }

        .connection-status.disconnected {
            background: #f8d7da;
            color: #721c24;
        }

        .connection-status.connecting {
            background: #fff3cd;
            color: #856404;
        }

        .top-section {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }

        .system-messages {
            flex: 1;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border: 2px solid #007bff;
        }

        .create-room {
            flex: 1;
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border: 2px solid #ffc107;
        }

        .system-messages h2 {
            margin-bottom: 15px;
            color: #333;
            font-size: 1.2em;
        }

        .main-content {
            display: flex;
            gap: 20px;
            margin-bottom: 30px;
        }

        .content-left {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            border: 2px solid #28a745;
            padding: 15px;
            border-radius: 8px;
        }

        .content-right {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            border: 2px solid #dc3545;
            padding: 15px;
            border-radius: 8px;
        }

        .available-rooms, .my-rooms {
            margin-bottom: 20px;
        }

        .available-rooms h2, .my-rooms h2 {
            color: #333;
            margin-bottom: 15px;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }

        .rooms-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .room-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            transition: all 0.3s ease;
        }

        .room-item:hover {
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }

        .room-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .room-item-title {
            font-weight: bold;
            color: #333;
        }

        .room-item-status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            font-weight: bold;
        }

        .room-item-status.status-waiting {
            background: #fff3cd;
            color: #856404;
        }

        .room-item-status.status-playing {
            background: #d4edda;
            color: #155724;
        }

        .room-item-status.status-finished {
            background: #f8d7da;
            color: #721c24;
        }

        .room-item-info {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .room-item-actions {
            display: flex;
            gap: 10px;
        }

        .room-item-actions .btn {
            flex: 1;
            padding: 8px 12px;
            font-size: 0.9em;
        }

        .btn-disabled {
            background: #6c757d !important;
            color: white !important;
            cursor: not-allowed !important;
            opacity: 0.6;
        }

        .player-guessed {
            background: #d4edda !important;
            border-color: #c3e6cb !important;
        }

        .player-guessed .room-player-name {
            color: #155724 !important;
        }
        
        .rooms-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .room-section {
            background: #fff;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
        
        .room-area {
            background: #fff;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .room-area:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.15);
        }
        
        .room-area.active {
            border-color: #667eea;
            background: #f8f9ff;
        }
        
        .room-area.creator {
            border-color: #ffc107;
            background: #fffbf0;
        }
        
        .room-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .room-title {
            font-size: 1.2em;
            font-weight: bold;
            color: #333;
        }
        
        .room-type {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8em;
            font-weight: bold;
        }
        
        .type-creator {
            background: #fff3cd;
            color: #856404;
        }
        
        .type-player {
            background: #d4edda;
            color: #155724;
        }
        
        .room-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 15px;
            font-size: 0.8em;
            font-weight: bold;
            text-transform: uppercase;
            margin-bottom: 10px;
        }
        
        .room-info {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 15px;
        }
        
        .room-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .room-actions .btn {
            flex: 1;
            min-width: 80px;
            font-size: 0.9em;
            padding: 6px 12px;
        }
        
        .room-game-content {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #e9ecef;
        }
        
        .room-game-status {
            text-align: center;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-weight: bold;
            font-size: 0.9em;
        }
        
        .room-guess-section {
            margin-bottom: 15px;
        }
        
        .room-guess-input {
            display: flex;
            gap: 8px;
            margin-bottom: 10px;
        }
        
        .room-guess-input input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 0.9em;
        }
        
        .room-guess-input input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }
        
        .room-guess-input .btn {
            padding: 8px 12px;
            font-size: 0.9em;
        }
        
        .room-players-list {
            max-height: 150px;
            overflow-y: auto;
            margin-bottom: 15px;
        }
        
        .room-player-item {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 6px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 0.9em;
            transition: all 0.3s ease;
            border-left: 3px solid #667eea;
        }
        
        .room-player-item.player-guessed {
            background: #e8f5e8;
            border-left-color: #28a745;
        }
        
        .player-status {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 12px;
            font-weight: 500;
        }
        
        .player-status.guessed {
            background: #28a745;
            color: white;
        }
        
        .btn-disabled {
            background: #6c757d !important;
            border-color: #6c757d !important;
            cursor: not-allowed !important;
            opacity: 0.6;
        }
        
        .room-player-name {
            font-weight: bold;
            color: #333;
        }
        
        .room-player-guess {
            color: #666;
            font-size: 0.8em;
        }
        
        .room-player-creator {
            color: #ffc107;
            font-weight: bold;
        }
        
        .room-messages {
            max-height: 120px;
            overflow-y: auto;
            background: #f8f9fa;
            border-radius: 6px;
            padding: 10px;
            margin-bottom: 15px;
        }
        
        .room-message {
            background: white;
            padding: 6px 8px;
            margin-bottom: 6px;
            border-radius: 4px;
            border-left: 3px solid #667eea;
            font-size: 0.8em;
        }
        
        .room-message.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        
        .room-message.success {
            border-left-color: #28a745;
            background: #d4edda;
        }
        
        .room-message.warning {
            border-left-color: #ffc107;
            background: #fff3cd;
        }

        .room-section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .room-list {
            max-height: 400px;
            overflow-y: auto;
        }

        .room-item {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .room-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .room-item.my-room {
            border-color: #28a745;
            background: #f8fff8;
        }

        .room-item.my-room:hover {
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.2);
        }

        .room-item.active {
            border-color: #667eea;
            background: #e3f2fd;
        }

        .room-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .room-name {
            font-weight: bold;
            color: #333;
            font-size: 1.1em;
        }

        .room-id {
            color: #666;
            font-size: 0.9em;
        }

        .room-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 15px;
            font-size: 0.8em;
            font-weight: bold;
            text-transform: uppercase;
        }


        .room-info {
            color: #666;
            font-size: 0.9em;
            margin-bottom: 10px;
        }

        .room-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 0.9em;
            font-weight: bold;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a6fd8;
            transform: translateY(-1px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
            transform: translateY(-1px);
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-warning:hover {
            background: #e0a800;
            transform: translateY(-1px);
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-1px);
        }


        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: bold;
        }

        .form-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .messages {
            background: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            max-height: 200px;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .message {
            background: white;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .message.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }

        .message.success {
            border-left-color: #28a745;
            background: #d4edda;
            color: #155724;
        }
        
        .message.info {
            border-left-color: #17a2b8;
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .message.warning {
            border-left-color: #ffc107;
            background: #fff3cd;
            color: #856404;
        }



        .game-section {
            background: #fff;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .game-status {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            font-weight: bold;
            font-size: 1.1em;
        }


        .guess-section {
            margin-bottom: 20px;
        }

        .guess-input {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .guess-input input {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1em;
        }

        .guess-input input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .players-list {
            max-height: 200px;
            overflow-y: auto;
            margin-bottom: 20px;
        }

        .player-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .player-name {
            font-weight: bold;
            color: #333;
        }

        .player-guess {
            color: #666;
            font-size: 0.9em;
        }

        .player-creator {
            color: #ffc107;
            font-weight: bold;
        }

        .game-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .game-actions .btn {
            flex: 1;
            min-width: 120px;
        }

        @media (max-width: 1200px) {
            .rooms-container {
                grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            }
        }

        @media (max-width: 768px) {
            .rooms-container {
                grid-template-columns: 1fr;
            }
            
            .room-actions {
                flex-direction: column;
            }
            
            .room-actions .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="connection-status" id="connectionStatus">连接中...</div>
    
    <div class="container">
        <div class="header">
            <h1>STOMP练习项目-猜数字游戏</h1>
            <p>完整版 - 支持房间管理和游戏功能</p>
        </div>

        <div class="connection-control">
            <div class="form-group">
                <label for="playerNameInput">玩家名称:</label>
                <input type="text" id="playerNameInput" placeholder="请输入玩家名称" value="">
            </div>
            <div class="connection-buttons">
                <button class="btn btn-success" id="connectBtn" onclick="connect()">连接游戏</button>
                <button class="btn btn-danger" id="disconnectBtn" onclick="disconnect()" style="display: none;">断开连接</button>
            </div>
            <div class="connection-status" id="connectionStatus">未连接</div>
        </div>

        <!-- 顶部操作区域 -->
        <div class="top-section">
            <div class="create-room">
                <h2>创建新房间</h2>
                <p style="color: #666; margin-bottom: 15px;">系统将自动生成房间名称</p>
                <button class="btn btn-primary" onclick="createRoom()">创建房间</button>
            </div>

            <div class="system-messages">
                <h2>📢 系统消息</h2>
                <div class="messages" id="messages">
                    <div class="message">欢迎来到猜数字游戏！创建房间或加入现有房间开始游戏吧！</div>
                </div>
            </div>
        </div>

        <div class="main-content">
            <div class="content-left">
                <div class="available-rooms">
                    <h2>游戏房间列表</h2>
                    <div class="rooms-list" id="availableRoomsList">
                        <!-- 游戏房间列表将通过JavaScript动态生成 -->
                    </div>
                </div>
            </div>
            
            <div class="content-right">
                <div class="my-rooms">
                    <h2>我参与的房间</h2>
                    <div class="rooms-container" id="roomsContainer">
                        <!-- 我的房间区域将通过JavaScript动态生成 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/js/stomp.min.js"></script>
    <script>
        /**
         * 房间管理系统前端JavaScript
         * 
         * 主要功能：
         * 1. WebSocket连接管理
         * 2. 房间创建、加入、离开、解散
         * 3. 实时消息处理和UI更新
         * 4. 连接状态监控和自动重连
         * 
         * 注意：游戏功能（开始游戏、猜数字等）为预留功能，当前显示提示信息
         */
        
        // ==================== 全局变量 ====================
        let stompClient = null;           // STOMP客户端
        let playerName = '';              // 当前玩家名称
        let connectionEstablished = false; // 连接是否已建立
        let isConnected = false;          // 连接状态
        let connectionCheckInterval = null; // 连接检查定时器
        
        // 本地房间列表管理
        let allRoomsList = []; // 所有游戏房间列表
        let myRoomsList = []; // 我参与的房间列表
        let subscribedRooms = new Set(); // 已订阅的房间列表

        // ==================== 连接管理 ====================
        
        /**
         * 连接WebSocket服务器
         * 建立STOMP连接并订阅相关消息
         */
        function connect() {
            const playerNameInput = document.getElementById('playerNameInput');
            const playerNameValue = playerNameInput.value.trim();
            
            if (!playerNameValue) {
                showErrorMessage('请输入玩家名称');
                return;
            }
            
            if (isConnected) {
                showErrorMessage('已经连接，请先断开连接');
                return;
            }
            
            updateConnectionStatus('connecting');
            playerName = playerNameValue;
            
            try {
                // 使用原生WebSocket连接
                const socket = new WebSocket('ws://' + window.location.host + '/ws');
                
                stompClient = Stomp.over(socket);
                
                const headers = {
                    'accept-version': '1.2', // 使用STOMP 1.2协议
                    'heart-beat': '10000,10000',
                    // 关键：告诉STOMP.js使用前缀模式
                    'user-prefix': '/user'
                };
                stompClient.connect(headers, function(frame) {
                    updateConnectionStatus('connected');
                    connectionEstablished = true;
                    isConnected = true;
                    
                    // 禁用玩家名输入
                    document.getElementById('playerNameInput').disabled = true;
                    
                    // 切换按钮状态
                    document.getElementById('connectBtn').style.display = 'none';
                    document.getElementById('disconnectBtn').style.display = 'inline-block';
                    
                    // 添加连接断开监听器
                    stompClient.ws.onclose = function(event) {
                        console.log('WebSocket连接已断开:', event);
                        handleConnectionLost();
                    };
                    
                    stompClient.ws.onerror = function(error) {
                        console.log('WebSocket连接错误:', error);
                        handleConnectionLost();
                    };
                    
                    // 启动连接状态检查
                    startConnectionCheck();
                    
                    
                    // 订阅个人消息 - 使用/user前缀，UserDestinationMessageHandler会自动转换
                    const personalDestination = '/user/queue/response';
                    const subscription = stompClient.subscribe(personalDestination, function(message) {
                        const data = JSON.parse(message.body);
                        handleResponse(data);
                    });
                    
                    // 订阅房间列表更新广播
                    stompClient.subscribe('/topic/roomUpdate', function(message) {
                        const data = JSON.parse(message.body);
                        console.log('收到房间更新广播:', data);
                        
                        if (data.type === 'ROOM_CREATE' && data.data) {
                            // 广播消息：更新房间列表，如果是新房间则添加，如果已存在则更新
                            updateRoomFromBroadcast(data.data);
                        } else if (data.type === 'ROOM_UPDATE' && data.data) {
                            // 广播消息：更新房间信息到本地列表
                            updateRoomFromBroadcast(data.data);
                        } else if (data.type === 'ROOM_DISSOLVE' && data.data) {
                            // 广播消息：从本地列表中移除房间
                            console.log('收到房间解散广播，房间ID:', data.data.roomId);
                            
                            // 检查是否是自己参与的房间
                            const isMyRoom = myRoomsList.some(room => room.roomId === data.data.roomId);
                            if (isMyRoom) {
                                addMessage(`房间 ${data.data.roomId} 已解散`, 'warning');
                            }
                            
                            removeRoomFromList(data.data.roomId);
                        }
                    });
                    
                    // 发送连接请求到后端
                    const connectMessage = {
                        type: 'CONNECT',
                        data: playerName
                    };
                    stompClient.send('/app/connect', {}, JSON.stringify(connectMessage));
                    
                    // 初始化时获取所有游戏房间列表
                    getAllRooms();
                    
                }, function(error) {
                    updateConnectionStatus('disconnected');
                    setTimeout(connect, 5000);
                });
            } catch (error) {
                updateConnectionStatus('disconnected');
                    showErrorMessage('连接失败: ' + error.message);
            }
        }

        // 启动连接状态检查
        function startConnectionCheck() {
            // 清除之前的检查
            if (connectionCheckInterval) {
                clearInterval(connectionCheckInterval);
            }
            
            // 每5秒检查一次连接状态
            connectionCheckInterval = setInterval(function() {
                if (isConnected && stompClient) {
                    // 检查WebSocket连接状态
                    if (stompClient.ws.readyState === WebSocket.CLOSED || 
                        stompClient.ws.readyState === WebSocket.CLOSING) {
                        console.log('检测到连接已断开，readyState:', stompClient.ws.readyState);
                        handleConnectionLost();
                    }
                }
            }, 5000);
        }

        // 停止连接状态检查
        function stopConnectionCheck() {
            if (connectionCheckInterval) {
                clearInterval(connectionCheckInterval);
                connectionCheckInterval = null;
            }
        }

        // 处理连接丢失
        function handleConnectionLost() {
            console.log('处理连接丢失');
            
            // 停止连接检查
            stopConnectionCheck();
            
            // 重置状态
            isConnected = false;
            connectionEstablished = false;
            
            // 启用玩家名输入
            document.getElementById('playerNameInput').disabled = false;
            
            // 切换按钮状态
            document.getElementById('connectBtn').style.display = 'inline-block';
            document.getElementById('disconnectBtn').style.display = 'none';
            
            // 清空房间列表
            document.getElementById('roomsContainer').innerHTML = '';
            document.getElementById('availableRoomsList').innerHTML = '';
            
            updateConnectionStatus('disconnected');
            addMessage('连接已断开，请重新连接', 'error');
            
            // 清空本地房间列表
            allRoomsList = [];
            myRoomsList = [];
        }

        // 断开连接
        function disconnect() {
            // 停止连接检查
            stopConnectionCheck();
            
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            
            // 重置状态
            isConnected = false;
            connectionEstablished = false;
            playerName = '';
            
            // 启用玩家名输入
            document.getElementById('playerNameInput').disabled = false;
            
            // 切换按钮状态
            document.getElementById('connectBtn').style.display = 'inline-block';
            document.getElementById('disconnectBtn').style.display = 'none';
            
            // 清空房间列表
            document.getElementById('roomsContainer').innerHTML = '';
            document.getElementById('availableRoomsList').innerHTML = '';
            
            updateConnectionStatus('disconnected');
            addMessage('已断开连接', 'info');
        }

        // 更新连接状态
        function updateConnectionStatus(status) {
            const statusElement = document.getElementById('connectionStatus');
            statusElement.className = 'connection-status';
            
            switch(status) {
                case 'connected':
                    statusElement.textContent = '已连接';
                    statusElement.classList.add('connected');
                    break;
                case 'disconnected':
                    statusElement.textContent = '未连接';
                    statusElement.classList.add('disconnected');
                    break;
                case 'connecting':
                    statusElement.textContent = '连接中...';
                    statusElement.classList.add('connecting');
                    break;
            }
        }

        // 添加房间到本地列表（单播消息使用）
        function addRoomToList(room) {
            // 检查房间是否已存在
            const existingIndex = allRoomsList.findIndex(r => r.roomId === room.roomId);
            if (existingIndex >= 0) {
                // 更新现有房间
                allRoomsList[existingIndex] = room;
            } else {
                // 添加新房间
                allRoomsList.push(room);
            }
            
            // 更新UI
            updateAvailableRoomsList(allRoomsList);
            updateMyRoomsList(allRoomsList);
        }

        // 从广播消息更新房间（广播消息使用）
        function updateRoomFromBroadcast(room) {
            // 检查是否是当前用户创建的房间
            const isMyRoom = room.creatorName === playerName;
            room.currentUserCreator = isMyRoom;
            
            // 检查房间是否已存在
            const existingIndex = allRoomsList.findIndex(r => r.roomId === room.roomId);
            if (existingIndex >= 0) {
                // 更新现有房间的状态和人数
                allRoomsList[existingIndex] = room;
            } else {
                // 添加新房间到列表
                allRoomsList.push(room);
            }
            
            // 更新UI
            updateAvailableRoomsList(allRoomsList);
            updateMyRoomsList(allRoomsList);
        }

        // 从本地列表中移除房间
        function removeRoomFromList(roomId) {
            console.log('移除房间:', roomId);
            
            // 从所有房间列表中移除
            allRoomsList = allRoomsList.filter(room => room.roomId !== roomId);
            
            // 从我参与的房间列表中移除
            myRoomsList = myRoomsList.filter(room => room.roomId !== roomId);
            
            // 更新UI
            updateAvailableRoomsList(allRoomsList);
            updateMyRoomsList(myRoomsList);
            
            console.log('房间移除后，allRoomsList长度:', allRoomsList.length);
            console.log('房间移除后，myRoomsList长度:', myRoomsList.length);
        }

        // 创建房间
        function createRoom() {
            if (!isConnected) {
                showErrorMessage('请先连接游戏');
                return;
            }
            
            // 检查是否已经创建了房间
            const hasCreatedRoom = myRoomsList.some(room => room.currentUserCreator);
            if (hasCreatedRoom) {
                showErrorMessage('您已经创建了房间，不能创建更多房间');
                return;
            }
            
            // 检查是否已经加入了房间
            const hasJoinedRoom = myRoomsList.some(room => !room.currentUserCreator);
            if (hasJoinedRoom) {
                showErrorMessage('您已经加入了其他房间，不能创建新房间');
                return;
            }
            
            // 直接发送创建房间请求，不需要房间名称
            const createMessage = {
                type: 'CREATE',
                data: ''
            };
            stompClient.send('/app/create', {}, JSON.stringify(createMessage));
        }

        // 加入房间
        function joinRoom(roomId) {
            if (!isConnected) {
                showErrorMessage('请先连接游戏');
                return;
            }
            
            // 检查房间是否存在且可加入
            const room = allRoomsList.find(r => r.roomId === roomId);
            if (!room) {
                showErrorMessage('房间不存在');
                return;
            }
            
            // 检查房间状态
            if (room.status !== 'WAITING') {
                showErrorMessage('只能加入等待中的房间');
                return;
            }
            
            // 检查房间是否已满
            const playerCount = room.players ? Object.keys(room.players).length : 0;
            if (playerCount >= 8) {
                showErrorMessage('房间已满');
                return;
            }
            
            // 检查是否已经创建了房间
            const hasCreatedRoom = myRoomsList.some(room => room.currentUserCreator);
            if (hasCreatedRoom) {
                showErrorMessage('您已经创建了房间，不能加入其他房间');
                return;
            }
            
            // 检查是否已经加入了房间
            const hasJoinedRoom = myRoomsList.some(room => !room.currentUserCreator);
            if (hasJoinedRoom) {
                showErrorMessage('您已经加入了其他房间，不能加入更多房间');
                return;
            }
            
            // 发送加入房间请求
            const joinMessage = {
                type: 'JOIN',
                data: roomId
            };
            stompClient.send('/app/join', {}, JSON.stringify(joinMessage));
            
            // 订阅房间消息
            subscribeToRoom(roomId);
        }

        
        // 订阅房间消息
        function subscribeToRoom(roomId) {
            // 检查是否已经订阅过这个房间
            if (subscribedRooms.has(roomId)) {
                return;
            }
            
            // 订阅房间消息（允许多房间并行订阅）
            stompClient.subscribe('/room/' + roomId, function(message) {
                const data = JSON.parse(message.body);
                handleRoomMessage(data);
            });
            
            // 记录已订阅的房间
            subscribedRooms.add(roomId);
        }

        // ==================== 游戏功能 ====================
        
        /**
         * 停止游戏
         * 
         * @param {string} roomId 房间ID
         */
        function stopGame(roomId) {
            if (!roomId) {
                showErrorMessage('房间ID不能为空');
                return;
            }
            
            if (!isConnected || !stompClient.connected) {
                showErrorMessage('WebSocket连接已断开，请重新连接');
                return;
            }
            
            const message = {
                type: 'STOP_GAME',
                data: roomId
            };
            
            console.log('发送停止游戏消息:', message);
            stompClient.send('/app/room/' + roomId, {}, JSON.stringify(message));
        }

        /**
         * 开始游戏
         * 
         * @param {string} roomId 房间ID
         */
        function startGame(roomId) {
            if (!roomId) {
                showErrorMessage('房间ID不能为空');
                return;
            }
            
            if (!isConnected || !stompClient.connected) {
                showErrorMessage('WebSocket连接已断开，请重新连接');
                return;
            }
            
            const message = {
                type: 'START_GAME',
                data: roomId
            };
            
            console.log('发送开始游戏消息:', message);
            stompClient.send('/app/room/' + roomId, {}, JSON.stringify(message));
        }

        // 解散房间
        function dissolveRoom(roomId) {
            if (!roomId) {
                showErrorMessage('房间ID不能为空');
                return;
            }
            
            if (!isConnected || !stompClient.connected) {
                showErrorMessage('WebSocket连接已断开，请重新连接');
                return;
            }
            
            if (confirm('确定要解散房间吗？')) {
                const message = {
                    type: 'DISSOLVE',
                    data: roomId
                };
                
                console.log('发送解散房间消息:', message);
                // 通过房间订阅发送消息
                stompClient.send('/app/room/' + roomId, {}, JSON.stringify(message));
            }
        }


        // 离开房间
        function leaveRoom(roomId) {
            if (!roomId) {
                showErrorMessage('房间ID不能为空');
                return;
            }
            
            if (!isConnected || !stompClient.connected) {
                showErrorMessage('WebSocket连接已断开，请重新连接');
                return;
            }
            
            const message = {
                type: 'LEAVE',
                data: roomId
            };
            
            // 通过房间订阅发送消息
            stompClient.send('/app/room/' + roomId, {}, JSON.stringify(message));
        }

        // 获取房间列表
        function getRooms() {
            stompClient.send('/app/rooms', {}, JSON.stringify({}));
        }

        // 获取所有房间列表
        function getAllRooms() {
            const getAllRoomsMessage = {
                type: 'GET_ALL_ROOMS',
                data: ''
            };
            stompClient.send('/app/allRooms', {}, JSON.stringify(getAllRoomsMessage));
        }

        // 处理响应消息
        function handleResponse(data) {
            
            switch(data.type) {
                case 'CONNECT_RESPONSE':
                    addMessage(data.data.info || '连接成功', 'success');
                    // 连接成功后获取所有房间列表
                    getAllRooms();
                    break;
                    
                case 'ROOMS_LIST':
                    if (data.data && Array.isArray(data.data)) {
                        // 更新本地房间列表
                        allRoomsList = data.data;
                        updateAvailableRoomsList(allRoomsList);
                        updateMyRoomsList(allRoomsList); // 同时更新"我参与的房间"列表
                    }
                    break;
                    
                    
                case 'ROOM_JOIN':
                    addMessage(`成功加入房间 ${data.data.roomId}，当前房间人数: ${data.data.players ? Object.keys(data.data.players).length : 0}`, 'success');
                    // 单播消息：将房间信息加到我参与的房间列表
                    if (data.data && data.data.roomId) {
                        // 标记为当前用户参与的房间（非创建者）
                        data.data.currentUserCreator = false;
                        addRoomToList(data.data);
                        subscribeToRoom(data.data.roomId);
                    }
                    break;
                    
                case 'ROOM_CREATE':
                    addMessage(`成功创建房间 ${data.data.roomId}，当前房间人数: ${data.data.players ? Object.keys(data.data.players).length : 0}`, 'success');
                    // 单播消息：将房间信息加到我参与的房间列表
                    if (data.data && data.data.roomId) {
                        // 标记为当前用户创建的房间
                        data.data.currentUserCreator = true;
                        addRoomToList(data.data);
                        subscribeToRoom(data.data.roomId);
                    }
                    break;
                    
                case 'ROOM_LEAVE':
                    addMessage(`成功离开房间 ${data.data.roomId}`, 'success');
                    break;
                    
                case 'GUESS_RESULT':
                    // 个人猜测结果处理（通过个人消息订阅接收）
                    if (data.data && data.data.roomId) {
                        const roomId = data.data.roomId;
                        const message = data.data.message;
                        const result = data.data.result;
                        
                        if (result) { // result为Boolean，true表示猜对
                            addRoomMessage(roomId, `🎉 ${message}`, 'success');
                            // 猜对了，该玩家不能再猜测
                            const guessInput = document.getElementById(`guessInput_${roomId}`);
                            const guessBtn = document.getElementById(`guessBtn_${roomId}`);
                            if (guessInput && guessBtn) {
                                guessInput.disabled = true;
                                guessBtn.disabled = true;
                                guessBtn.textContent = '已猜对';
                                guessBtn.classList.add('btn-disabled');
                            }
                        } else {
                            addRoomMessage(roomId, `💡 ${message}`, 'warning');
                            // 猜错了，该玩家可以继续猜测，不禁用按钮
                        }
                    } else {
                        addMessage(data.data.message, 'success');
                    }
                    break;
                    
                case 'ERROR':
                    showErrorMessage(data.data || '发生错误');
                    break;
                    
                default:
                    addMessage(data.content || '收到消息', 'info');
            }
        }
        
        // 处理房间消息
        function handleRoomMessage(data) {
            const roomId = data.data ? data.data.roomId : data.roomId;
            
            switch(data.type) {
                case 'GAME_START':
                    addRoomMessage(roomId, '🎮 游戏开始！请猜测1-100之间的数字', 'success');
                    
                    // 重置当前玩家的猜测状态
                    const guessInput = document.getElementById(`guessInput_${roomId}`);
                    const guessBtn = document.getElementById(`guessBtn_${roomId}`);
                    if (guessInput && guessBtn) {
                        guessInput.disabled = false;
                        guessBtn.disabled = false;
                        guessBtn.textContent = '猜测';
                        guessBtn.classList.remove('btn-disabled');
                        guessInput.value = '';
                    }
                    break;
                    
                case 'GAME_STOP':
                    addRoomMessage(roomId, '⏹️ 游戏已停止', 'warning');
                    
                    // 重置当前玩家的猜测状态
                    const stopGuessInput = document.getElementById(`guessInput_${roomId}`);
                    const stopGuessBtn = document.getElementById(`guessBtn_${roomId}`);
                    if (stopGuessInput && stopGuessBtn) {
                        stopGuessInput.disabled = true;
                        stopGuessBtn.disabled = true;
                        stopGuessBtn.textContent = '等待游戏开始';
                        stopGuessBtn.classList.add('btn-disabled');
                        stopGuessInput.value = '';
                    }
                    break;
                    
                // GAME_END 状态已移除，游戏只有 WAITING 和 PLAYING 两种状态
                    
                case 'ROOM_UPDATE':
                    // 检查房间人数变化，显示玩家加入或离开信息
                    if (data.data && data.data.players) {
                        const currentPlayerCount = Object.keys(data.data.players).length;
                        const roomElement = document.querySelector(`[data-room-id="${roomId}"]`);
                        if (roomElement) {
                            const playerCountElement = roomElement.querySelector('.room-info');
                            if (playerCountElement) {
                                const oldText = playerCountElement.textContent;
                                const match = oldText.match(/玩家数: (\d+)/);
                                if (match) {
                                    const oldCount = parseInt(match[1]);
                                    if (currentPlayerCount > oldCount) {
                                        addRoomMessage(roomId, `有玩家加入房间，当前人数: ${currentPlayerCount}`, 'success');
                                    } else if (currentPlayerCount < oldCount) {
                                        addRoomMessage(roomId, `有玩家离开房间，当前人数: ${currentPlayerCount}`, 'warning');
                                    }
                                }
                            }
                        }
                    }
                    addRoomMessage(roomId, '房间信息已更新', 'info');
                    break;
                    
                case 'ROOM_DISSOLVE':
                    addRoomMessage(roomId, '房间已解散', 'error');
                    break;
                    
                case 'ROOM_JOIN':
                    const joiningPlayerName = data.data.playerName || '未知玩家';
                    addRoomMessage(roomId, `玩家 ${joiningPlayerName} 加入房间`, 'success');
                    // 如果加入者是自己，需要更新"我参与的房间"列表
                    if (data.data.playerName === playerName) {
                        // 通过ROOM_UPDATED消息来更新，不需要调用getAllRooms()
                    }
                    break;
                    
                case 'ROOM_LEAVE':
                    const leavingPlayerName = data.data.playerName || '未知玩家';
                    addRoomMessage(roomId, `玩家 ${leavingPlayerName} 离开房间`, 'warning');
                    // 如果离开者是自己，需要更新"我参与的房间"列表
                    if (data.data.playerName === playerName) {
                        // 通过ROOM_UPDATED消息来更新，不需要调用getAllRooms()
                    }
                    break;
                    
                case 'GUESS_RESULT':
                    // 其他玩家的猜测结果处理（通过房间消息订阅接收）
                    if (data.data && data.data.roomId) {
                        const message = data.data.message;
                        const result = data.data.result;
                        
                        if (result) { // 猜对了
                            addRoomMessage(roomId, `🎯 ${message}`, 'success');
                        } else {
                            addRoomMessage(roomId, `🎯 ${message}`, 'info');
                        }
                    }
                    break;
                    
                default:
                    addRoomMessage(roomId, '收到房间消息', 'info');
            }
        }

        // 更新特定房间的玩家列表
        function updateRoomPlayerList(roomId, players) {
            // 找到对应的房间并更新玩家列表
            const roomElement = document.querySelector(`[data-room-id="${roomId}"]`);
            if (roomElement) {
                const playersListElement = roomElement.querySelector('.room-players-list');
                if (playersListElement) {
                    const playersArray = Object.values(players);
                    playersListElement.innerHTML = playersArray.map(player => `
                        <div class="room-player-item ${player.hasGuessed ? 'player-guessed' : ''}">
                            <div class="room-player-name ${player.isCreator ? 'room-player-creator' : ''}">
                                ${player.name} ${player.isCreator ? '👑' : ''}
                            </div>
                            <div class="room-player-guess">
                                ${player.guess ? `猜测: ${player.guess} (${player.guessResult || '未知'})` : '未猜测'}
                            </div>
                            ${player.hasGuessed ? `<div class="player-status guessed">✓ 已猜测</div>` : ''}
                        </div>
                    `).join('');
                }
            }
        }

        // 更新我参与的房间列表
        function updateMyRoomsList(rooms) {
            
            if (!rooms || rooms.length === 0) {
                myRoomsList = [];
                updateRoomLists([]);
                updateCreateRoomButton();
                return;
            }
            
            // 过滤出我参与的房间（我创建的房间 + 我加入的房间）
            const myRooms = rooms.filter(room => {
                
                // 我创建的房间
                if (room.currentUserCreator) {
                    return true;
                }
                // 我加入的房间（检查玩家列表中是否有我）
                if (room.players) {
                    const playerNames = Object.values(room.players).map(p => p.name);
                    const isInRoom = Object.values(room.players).some(player => player.name === playerName);
                    return isInRoom;
                }
                return false;
            });
            
            // 排序：自己的房间（创建的房间）在前，参与的房间在后
            myRooms.sort((a, b) => {
                const aIsMyRoom = a.currentUserCreator || a.creatorName === playerName;
                const bIsMyRoom = b.currentUserCreator || b.creatorName === playerName;
                
                if (aIsMyRoom && !bIsMyRoom) return -1; // a是自己的房间，排在前面
                if (!aIsMyRoom && bIsMyRoom) return 1;  // b是自己的房间，排在前面
                return 0; // 都是或都不是自己的房间，保持原顺序
            });
            
            myRoomsList = myRooms;
            updateRoomLists(myRooms);
            updateCreateRoomButton();
        }

        // 更新创建房间按钮状态（保持正常样式，不显示限制状态）
        function updateCreateRoomButton() {
            // 完全移除按钮状态更新逻辑，保持按钮始终正常
            // 所有限制检查都在点击时进行
        }

        // 更新房间列表
        function updateRoomLists(rooms) {
            const roomsContainer = document.getElementById('roomsContainer');
            
            if (!rooms || rooms.length === 0) {
                roomsContainer.innerHTML = '<p style="text-align: center; color: #666; padding: 40px; grid-column: 1 / -1;">暂无房间</p>';
                return;
            }
            
            // 为每个房间创建独立的操作区域
            roomsContainer.innerHTML = rooms.map(room => {
                // 使用多种方式判断是否为创建者，确保准确性
                const isCreator = room.currentUserCreator || room.creatorName === playerName;
                const playerCount = room.players ? Object.keys(room.players).length : 0;
                const players = room.players ? Object.values(room.players) : [];
                
                // 检查当前玩家是否已猜测
                const currentPlayer = players.find(p => p.name === playerName);
                const hasCurrentPlayerGuessed = currentPlayer ? currentPlayer.hasGuessed : false;
                
                // 检查当前玩家是否已猜对（只有猜对了才不能再次猜测）
                const hasCurrentPlayerGuessedCorrectly = currentPlayer && currentPlayer.hasGuessed && 
                    currentPlayer.guessResult === '正确';
                
                console.log(`房间 ${room.roomId} 调试信息:`, {
                    currentPlayer,
                    hasGuessed: currentPlayer ? currentPlayer.hasGuessed : false,
                    guessResult: currentPlayer ? currentPlayer.guessResult : null,
                    hasCurrentPlayerGuessedCorrectly
                });
                
                return `
                    <div class="room-area ${isCreator ? 'creator' : ''}" data-room-id="${room.roomId}">
                        <div class="room-header">
                            <div class="room-title">${room.roomName || room.roomId}</div>
                            <div class="room-type ${isCreator ? 'type-creator' : 'type-player'}">
                                ${isCreator ? '创建者' : '参与者'}
                            </div>
                        </div>
                        
                        <div class="room-status status-${room.status.toLowerCase()}">
                            ${getStatusText(room.status)}
                        </div>
                        
                        <div class="room-info">
                            房间ID: ${room.roomId}<br>
                            玩家数: ${playerCount}
                        </div>
                        
                        <div class="room-actions">
                            ${isCreator ? `
                                ${room.status === 'PLAYING' ? `
                                    <button class="btn btn-warning" onclick="stopGame('${room.roomId}')">停止游戏</button>
                                ` : `
                                    <button class="btn btn-success" onclick="startGame('${room.roomId}')">开始游戏</button>
                                `}
                                <button class="btn btn-danger" onclick="dissolveRoom('${room.roomId}')">解散房间</button>
                            ` : currentPlayer ? `
                                <button class="btn btn-secondary" onclick="leaveRoom('${room.roomId}')">离开房间</button>
                            ` : `
                                <button class="btn btn-primary" onclick="joinRoom('${room.roomId}')">加入房间</button>
                            `}
                        </div>
                        
                        <div class="room-game-content">
                            <div class="room-game-status status-${room.status.toLowerCase()}">
                                ${getGameStatusText(room.status)}
                            </div>
                            
                            <div class="room-guess-section">
                                <div class="room-guess-input">
                                    <input type="number" id="guessInput_${room.roomId}" placeholder="输入1-100的数字" min="1" max="100" ${room.status !== 'PLAYING' || hasCurrentPlayerGuessedCorrectly ? 'disabled' : ''}>
                                    <button class="btn btn-primary" id="guessBtn_${room.roomId}" onclick="submitGuess('${room.roomId}')" ${room.status !== 'PLAYING' || hasCurrentPlayerGuessedCorrectly ? 'disabled' : ''}>${hasCurrentPlayerGuessedCorrectly ? '已猜对' : (room.status === 'PLAYING' ? '猜测' : '等待游戏开始')}</button>
                                </div>
                            </div>
                            
                            <div class="room-players-list">
                                ${players.map(player => `
                                    <div class="room-player-item ${player.hasGuessed ? 'player-guessed' : ''}">
                                        <div class="room-player-name ${player.isCreator ? 'room-player-creator' : ''}">
                                            ${player.name} ${player.isCreator ? '👑' : ''}
                                        </div>
                                        <div class="room-player-guess">
                                            ${player.guess ? `猜测: ${player.guess} (${player.guessResult || '未知'})` : '未猜测'}
                                        </div>
                                        ${player.hasGuessed ? `<div class="player-status guessed">✓ 已猜测</div>` : ''}
                                    </div>
                                `).join('')}
                            </div>
                            
                            <div class="room-messages" id="roomMessages_${room.roomId}">
                                <div class="room-message">房间消息将在这里显示</div>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');
            
        }

        // 更新游戏房间列表
        function updateAvailableRoomsList(rooms) {
            const availableRoomsList = document.getElementById('availableRoomsList');
            
            if (!rooms || rooms.length === 0) {
                availableRoomsList.innerHTML = '<p style="text-align: center; color: #666; padding: 40px;">暂无游戏房间</p>';
                return;
            }
            
            // 显示所有房间（包括自己创建的房间）
            // 因为创建房间后，创建者默认就加入了房间，所以应该显示在游戏房间列表中
            
            if (rooms.length === 0) {
                availableRoomsList.innerHTML = '<p style="text-align: center; color: #666; padding: 40px;">暂无游戏房间</p>';
                return;
            }
            
            // 排序：自己的房间在前，其他房间在后
            const sortedRooms = [...rooms].sort((a, b) => {
                const aIsMyRoom = a.currentUserCreator || a.creatorName === playerName;
                const bIsMyRoom = b.currentUserCreator || b.creatorName === playerName;
                
                if (aIsMyRoom && !bIsMyRoom) return -1; // a是自己的房间，排在前面
                if (!aIsMyRoom && bIsMyRoom) return 1;  // b是自己的房间，排在前面
                return 0; // 都是或都不是自己的房间，保持原顺序
            });
            
            // 为所有房间创建房间项
            availableRoomsList.innerHTML = sortedRooms.map(room => {
                const playerCount = room.players ? Object.keys(room.players).length : 0;
                const maxPlayers = 8; // 假设最大玩家数为8
                const canJoin = playerCount < maxPlayers && room.status === 'WAITING';
                const isMyRoom = room.currentUserCreator || room.creatorName === playerName;
                
                return `
                    <div class="room-item ${isMyRoom ? 'my-room' : ''}" data-room-id="${room.roomId}">
                        <div class="room-item-header">
                            <div class="room-item-title">${room.roomName || room.roomId} ${isMyRoom ? '(我的房间)' : ''}</div>
                            <div class="room-item-status status-${room.status.toLowerCase()}">
                                ${getStatusText(room.status)}
                            </div>
                        </div>
                        
                        <div class="room-item-info">
                            房间ID: ${room.roomId}<br>
                            创建者: ${room.creatorName}<br>
                            玩家数: ${playerCount}/${maxPlayers}
                        </div>
                        
                        <div class="room-item-actions">
                            ${isMyRoom ? 
                                '<span style="color: #28a745; font-weight: bold;">我的房间</span>' : 
                                `<button class="btn btn-primary" onclick="joinRoom('${room.roomId}')">加入房间</button>`
                            }
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 获取状态文本
        function getStatusText(status) {
            switch(status) {
                case 'WAITING': return '等待中';
                case 'PLAYING': return '游戏中';
                default: return status;
            }
        }
        
        // 获取游戏状态文本
        function getGameStatusText(status) {
            switch(status) {
                case 'WAITING': return '⏳ 等待游戏开始';
                case 'PLAYING': return '🎮 游戏进行中';
                default: return status;
            }
        }
        
        /**
         * 提交猜测
         * 
         * @param {string} roomId 房间ID
         */
        function submitGuess(roomId) {
            const guessInput = document.getElementById(`guessInput_${roomId}`);
            const guessBtn = document.getElementById(`guessBtn_${roomId}`);
            const guess = parseInt(guessInput.value);
            
            // 检查是否已猜对
            if (guessBtn.disabled && guessBtn.textContent === '已猜对') {
                addRoomMessage(roomId, '您已经猜对了，不能再猜测', 'warning');
                return;
            }
            
            // 检查游戏状态 - 只有游戏进行中才能发送猜测
            const roomElement = document.querySelector(`[data-room-id="${roomId}"]`);
            if (roomElement) {
                const statusElement = roomElement.querySelector('.room-status');
                if (statusElement && !statusElement.classList.contains('status-playing')) {
                    addRoomMessage(roomId, '游戏未开始，无法发送猜测', 'error');
                    return;
                }
            }
            
            if (!guess || guess < 1 || guess > 100) {
                addRoomMessage(roomId, '请输入1-100之间的数字', 'error');
                return;
            }
            
            const message = {
                type: 'GUESS',
                data: guess,  // 传字符串格式的数字
            };
            
            // 通过房间订阅发送消息
            stompClient.send('/app/room/' + roomId, {}, JSON.stringify(message));
            
            addRoomMessage(roomId, `🎯 您猜测了数字 ${guess}`, 'success');
        }
        
        // 添加房间消息
        function addRoomMessage(roomId, content, type = 'info') {
            const messagesContainer = document.getElementById(`roomMessages_${roomId}`);
            if (!messagesContainer) return;
            
            const messageElement = document.createElement('div');
            messageElement.className = `room-message ${type}`;
            messageElement.textContent = `[${new Date().toLocaleTimeString()}] ${content}`;
            
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 获取当前会话ID

        // 添加消息到系统消息区域
        function addMessage(content, type = 'info') {
            const messagesContainer = document.getElementById('messages');
            const messageElement = document.createElement('div');
            messageElement.className = `message ${type}`;
            messageElement.textContent = `[${new Date().toLocaleTimeString()}] ${content}`;
            
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 显示错误弹出消息
        function showErrorMessage(message) {
            // 创建错误提示框
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-popup';
            errorDiv.textContent = message;
            errorDiv.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #dc3545;
                color: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
                z-index: 1000;
                font-weight: bold;
                max-width: 300px;
                word-wrap: break-word;
            `;
            
            document.body.appendChild(errorDiv);
            
            // 3秒后自动消失
            setTimeout(() => {
                if (errorDiv.parentNode) {
                    errorDiv.parentNode.removeChild(errorDiv);
                }
            }, 3000);
        }

        // 页面加载完成后初始化
        window.onload = function() {
            // 生成默认的玩家名称
            const timestamp = Date.now();
            document.getElementById('playerNameInput').value = `玩家_${timestamp}`;
            
            // 不自动连接，等待用户手动连接
            updateConnectionStatus('disconnected');
        };
    </script>
</body>
</html>
